package com.qf.controller;

import com.qf.dto.DtsPermissionDto;
import com.qf.dto.DtsSerachDto;
import com.qf.pojo.DtsRole;
import com.qf.service.RoleService;
import com.qf.util.*;
import com.qf.vo.PermVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * projectName: shop-manage
 *
 * @author: 元
 * time: 2021/9/15 0015 9:21
 * description:角色管理接口
 */
@RestController
@CrossOrigin("*")
@RequestMapping("/role")
public class AdminRoleController {

    public static final Logger logger = LoggerFactory.getLogger(AdminRoleController.class);

    @Autowired
    private RoleService roleService;
    @Autowired
    public ApplicationContext applicationContext;


    //管理员接口调用
    @RequestMapping("/options")
    public Object option(){
        List<DtsRole> roleList = roleService.findAllRoleList();
        logger.debug("[]查询数据为:{}",roleList);
        List<Map<String,Object>> resultList = new ArrayList<>();
        if (resultList != null){
            for (DtsRole dtsRole : roleList){
                Map<String,Object> data = new HashMap<>();
                data.put("values",dtsRole.getId());
                data.put("label",dtsRole.getName());
                resultList.add(data);
            }
        }
        logger.info("[角色列表]接口调用结束");
        return ResponseUtil.ok(resultList);
    }
    /**
     * 分页加模糊查询
     * */
    @RequestMapping("list")
    public Object list(DtsSerachDto serachDto){
        Map data = roleService.queryRolesByPage(serachDto);
        logger.info("[角色列表]分页查询数据为",data);
        return ResponseUtil.ok(data);
    }

    //新增角色
    @RequestMapping("create")
    public Object create(@RequestBody DtsRole dtsRole){
        //先进行角色存在判断
        String roleName = dtsRole.getName();
        if (roleName == null || roleName == ""){
            logger.warn("[新建角色]新建角色名为空");
            return ResponseUtil.fail();
        }
        boolean hasRoleName = roleService.checkRoleName(roleName);
        if (hasRoleName){
            logger.error("[新建角色]该角色已存在",roleName);

            return AdminResponseUtil.fail(AdminResponseCode.ROLE_NAME_EXIST);
        }
        roleService.addRole(dtsRole);
        logger.info("[新建角色]新增角色操作已结束",dtsRole);
        return ResponseUtil.ok(dtsRole);
    }

    /**
     * 删除角色信息
     * */
    @RequestMapping("delete")
    public Object delete(@RequestBody DtsRole dtsRole){
        int rows = roleService.removeRole(dtsRole.getId());
        if (rows == 0) {
            return ResponseUtil.fail();
        }
        logger.info("[删除角色]删除影响行数为:{}",rows);

        return ResponseUtil.ok();
    }

    /**
     * 修改角色信息
     * */
    @RequestMapping("update")
    public Object update(@RequestBody DtsRole dtsRole){
        int rows = roleService.updateRole(dtsRole);
        //返回结果
        if (rows == 0){
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok(dtsRole);
    }

    /**
     * 角色权限授予
     */
   @GetMapping("permissions")
   public Object show(int roleId){
       logger.info("[权限读取接口]开始调用!查询权限的角色id为:{}", roleId);
       if (roleId == 0){
            logger.warn("[权限读取接口]没有传递角色id!无法查询该角色拥有的权限!");
           return ResponseUtil.fail();
        }
       //查询已经写好的全部接口
       List<Permission> permissionList  = PermissionUtil.listPermission(applicationContext,"com.qf.controller");

       //处理结果集,变成层次展示类型 systemPermissions
        List<PermVo> permVos = PermissionUtil.listPermVo(permissionList);

       //判断是否是超级管理员
       boolean isSuper = roleService.checkSuper(roleId);
      //查询当前用户拥有权限的集合
        Set<String> assignedPermissions = new HashSet<>();
       if (isSuper) {
            for (Permission permission : permissionList) {
                //读取权限权限注解的value值
               assignedPermissions.add(permission.getRequiresPermissions().value()[0]);
            }
       }else{
          assignedPermissions = roleService.queryPermissions(roleId);
        }
        Map data = new HashMap();
        data.put("systemPermissions",permVos);
        data.put("assignedPermissions",assignedPermissions);
       logger.info("[权限读取接口]数据读取成功!最终数据为:{}", data);
      return  ResponseUtil.ok(data);
 }

    /**
     * 修改角色权限
     * */
    @PostMapping("permissions")
    public Object update(@RequestBody DtsPermissionDto dtsPermissionDto) {
        //1.参数校验
        if (dtsPermissionDto.getRoleId() == 0) {
            logger.error("[权限修改]传入的roleId为0,出现异常!");
            return ResponseUtil.badArgument();
        }
        //2.清空所有(注意超级管理员权限不可以改变)
        boolean isSuper = roleService.checkSuper(dtsPermissionDto.getRoleId());
        if (isSuper) {
            logger.warn("[权限修改]要修改的角色id:{},是超级管理员,没法修改!", dtsPermissionDto.getRoleId());
            return AdminResponseUtil.fail(AdminResponseCode.ROLE_SUPER_SUPERMISSION);
        }
        roleService.removePermisssion(dtsPermissionDto.getRoleId());
        roleService.savePermission(dtsPermissionDto);
        return ResponseUtil.ok(null);
    }




}
